package com.hsd.znsh.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsd.znsh.entity.User;
import com.hsd.znsh.service.PushService;
import com.hsd.znsh.service.RedisService;
import com.hsd.znsh.utils.ResultVOUtil;
import com.hsd.znsh.utils.SecurityUtil;
import com.hsd.znsh.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private RedisService redisService;

	@Autowired
	private PushService pushService;


	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		if(request.getRequestURI().indexOf("/app/")!=-1){
			String token=UUIDUtil.getUUID();
			User user=SecurityUtil.getUser();
			redisService.set(token,user);
			pushService.pushToUserInfo("系统警告","您的账号已经在另一台手机上登录，请注意密码是否泄漏，如若不是，请重新登录",user.getUsername());
			response.getWriter().write(objectMapper.writeValueAsString(ResultVOUtil.success(token)));
		}else{
			response.getWriter().write(objectMapper.writeValueAsString(ResultVOUtil.success()));
		}
	}

}
